package com.pet.platform.controller;

import com.pet.platform.common.PageResult;
import com.pet.platform.common.Result;
import com.pet.platform.dto.UserDTO;
import com.pet.platform.dto.UserQueryDTO;
import com.pet.platform.entity.User;
import com.pet.platform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Long id) {
        return Result.success(userService.findById(id));
    }
    
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<PageResult<UserDTO>> findPage(UserQueryDTO queryDTO) {
        return Result.success(userService.findPage(queryDTO));
    }
    
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> create(@Valid @RequestBody UserDTO userDTO) {
        // 检查用户名是否已存在
        User existingUser = userService.findByUsername(userDTO.getUsername());
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        UserQueryDTO queryDTO = new UserQueryDTO();
        queryDTO.setEmail(userDTO.getEmail());
        PageResult<UserDTO> result = userService.findPage(queryDTO);
        if (result.getTotal() > 0) {
            return Result.error("邮箱已被使用");
        }

        userService.create(userDTO);
        return Result.success();
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> update(@PathVariable Long id, @Valid @RequestBody UserDTO userDTO) {
        userService.update(id, userDTO);
        return Result.success();
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> delete(@PathVariable Long id) {
        userService.delete(id);
        return Result.success();
    }
    
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        userService.updateStatus(id, status);
        return Result.success();
    }
    
    @PostMapping("/change-password")
    public Result<Void> changePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
        userService.changePassword(oldPassword, newPassword);
        return Result.success();
    }
    
    @PostMapping("/avatar")
    public Result<String> updateAvatar(@RequestParam("file") MultipartFile file) {
        return Result.success(userService.updateAvatar(file));
    }
} 